import React, { useState, useRef, useMemo } from 'react';
import { useDispatch, useSelector, history } from 'umi';
import { Picture, Price } from '@/design';
import Pic_Hold from '@/assets/images/pic_hold.png';
import GoodsModal from './GoodsModal';
import SpecPicker from './specPicker';
import NumberPicker from '@/components/NumberPicker/NumberPicker';
import { isEmpty, flatten, getUmePic } from '@/utils/common';
import styles from './menu.less';


export default function CMenu(props: any) {
  const dispatch = useDispatch();
  const { categoryList } = props;
  let [ goodsModalVisable, setGoodsModalVisable] = useState<boolean>(false);
  let [ swiperImgs, setSwiperImgs] = useState([]);
  let [ goodsDetail, setGoodsDetail] = useState({});
  let [ specVisiable, setSpecVisiable ] = useState<boolean>(false);
  const { cartList } = useSelector((state:any) => state.cartList);

  const swiperRef = useRef<HTMLDivElement>(null);

  // 处理返回的图片成数组
  const getImages = (arr: any[]) => {
    const arrTemp = arr.reduce((acc, val) => {
      if(val) {
        acc.push(`${val}/600`);
      }
      return acc
    }, []);
    return arrTemp.length ? arrTemp : [Pic_Hold]
  }

  // 点击菜品图片
  const handleClickPicture = (_item: any) => {
    setGoodsModalVisable(true);
    let imgs = getImages([_item.productIcon1, _item.productIcon2, _item.productIcon3]);
    setSwiperImgs(imgs)
    setGoodsDetail(_item)
  }

  //加入购物车
  const addCartList = (goodDetail: any) => {
    const { productId, categoryId, productName, productIcon1, productPrice } = goodDetail;
    let good = {
      tasteList: [],
      categoryId,
      productIcon: productIcon1,
      productId,
      productName,
      productPrice,
      productQuantity: 1
    } 
    let tempMap = new Map();
    let carListObj = mapCartList(cartList);
    let cartItem =  carListObj[productId];
    let newCartList = JSON.parse(JSON.stringify(cartList));
    if(!isEmpty(cartItem)) {
      newCartList = newCartList.map((item:any) => {
        if(item.productId === productId) {
          return {
            ...item,
            productQuantity: item.productQuantity + 1
          }
        }
        return item
      })
    } else {
      newCartList.push(good)
    }
   
    // if(!isEmpty(cartItem)){
    //   tempMap.set(productId, {
    //     ...good,
    //     productQuantity: tempMap.get(`${productId}`).productQuantity + 1
    //   })
    // } else {
    //   tempMap.set(`${productId}`, good)
    // }
    // return 
    dispatch({
      type: 'cartList/saveCartList',
      payload: newCartList
    })

  }

    /* 展示/隱藏規格彈窗 */
  const handleClickAdd = (_item: any) => {
    if(isEmpty(_item.tasteCategoryList)) {//单规格的時候不顯示彈框
      addCartList(_item)
    } else {
      setGoodsDetail(_item);
      setSpecVisiable(true)
    }
  }

  const handleNumChange = (num: number, curSpec: any)=> {//这边只针对单规格商品
    let carListObj = mapCartList(cartList);
    const { productId } = curSpec;
    let newCartList = JSON.parse(JSON.stringify(cartList));
    if(num === 0) {
      newCartList = newCartList.filter((item:any)=>{
        return item.productId !== productId
      })
    }
    newCartList = newCartList.map((item: any)=>{
      let cartItem =  carListObj[item.productId].list[0];
      if(productId === item.productId) {
        return {
          ...item,
          productQuantity: num,
          num
        }
      } 
      return item
    })
    dispatch({
      type: 'cartList/saveCartList',
      payload: newCartList
    })
  }

  //將cartList的數據整合成key value productId ===> 數組
  const mapCartList = (array: any) => {
   return array.reduce((m:any, n:any) => {
      if (!m[n.productId]) {
        m[n.productId] = {list: []}
      }
      m[n.productId].list.push(n)
      return m
    }, {})
  }

  //渲染按鈕
  const getGoodsButton = (item:any) => {
    let newCartList = JSON.parse(JSON.stringify(cartList));
    let carListObj = mapCartList(newCartList);
    let cartItem =  carListObj[item.productId];
    const { tasteCategoryList } = item;
    if (isEmpty(cartItem)) {
      return <button className={styles.add_cart} onClick={()=>{handleClickAdd(item)}}></button>
    } else {
     
      let sum = cartItem.list.reduce((prev:any, cur:any) => {
        return prev + cur.productQuantity;
      }, 0)
      if(isEmpty(tasteCategoryList)) {//單規格的
        return <div className={styles.add_cart_icon_wrap}><NumberPicker value={sum} attr={item} onChange={handleNumChange} /></div>
      } else {
        return <div className={styles.add_cart_icon_wrap}>{getMuliButton(sum, item, 'P')}</div>
      }
    }
  }

  //
  const handleMuilSub = (productId: string) => {
    let newCartList = JSON.parse(JSON.stringify(cartList));
    let carListObj = mapCartList(newCartList);
    let cartItem =  carListObj[productId];
    let cartLg = cartItem.list.length; //当前这一产品在购物车总共的长度
    let lastItem = cartItem.list[cartLg - 1] ;//拿到最後一項
    let cartItemList:any =  [];
    if(lastItem.productQuantity === 1) { //等于1的时候
      cartItemList = [...cartItem.list.slice(0, cartLg - 1)]
    } else {
      lastItem = {
        ...lastItem,
        productQuantity: lastItem.productQuantity - 1
      }
      cartItemList =  [...cartItem.list.slice(0, cartLg - 1), lastItem];
    }
    carListObj[productId].list = cartItemList;
    newCartList = Object.values(carListObj).map((item:any)=>{
      return item.list
    })
    newCartList = newCartList.flat(Infinity)
    dispatch({
      type: 'cartList/saveCartList',
      payload: newCartList
    })
  }

  // 
  const linkToPack = (item: any) => {
    return history.push(`/mainpack/${item.productId}`)
  }

  //多規格的加和減
  const getMuliButton = (sum:number, item: any, type:string) => {
    return (<div className={`${styles.num_picker} ${props.className || ''}`}>
    <button
      type="button"
      className={styles.sub}
      onClick={() => {type !== 'PACK' ? handleMuilSub(item.productId) : ()=> {}}}
    >-</button>
    <input
      type="text"
      readOnly
      className={`${styles.num} ${props.hideNumber ? styles.hideNumber : ''}`}
      value={sum}
      maxLength={3}
    />
    <button
      type="button"
      className={styles.add}
      onClick={()=>{type !== 'PACK' ? handleClickAdd(item) : linkToPack(item)}}
    >+</button>
  </div>)
  }

  // 套餐的按钮显示
  const getPackButton = (item: any) => {
    let newCartList = JSON.parse(JSON.stringify(cartList));
    let carListObj = mapCartList(newCartList);
    let cartItem =  carListObj[item.productId];
    const { tasteCategoryList } = item;
    if (isEmpty(cartItem)) {
      return <button className={styles.choose_btn} onClick={() => linkToPack(item)}>選擇套餐</button>
    } else {
      let sum = cartItem.list.reduce((prev:any, cur:any) => {
        return prev + cur.productQuantity;
      }, 0)
      return <div className={styles.add_cart_icon_wrap}>{getMuliButton(sum, item, 'PACK')}</div>
    }
    
  }

  const renderDataRow = (_item:any, _index:number) => {
    return (<li className={styles._item_box} key={_index} style={{ animationDelay: `${_index % 10 / 10}s` }} >
      <div className={styles.img_box} onClick={()=>{handleClickPicture(_item)}}>
        <Picture className={styles.img} src={getUmePic(`${_item.productIcon1}`)} />
      </div>
      <div className={styles.info_box}>
        <h4 className={styles.title}>{_item.productName}</h4>
        <p>
          <span>月售  {_item.monthSaleAmount}</span>
          {_item.isShowStock ? <span>剩餘  {_item.stockNum}</span> : null}
        </p>
        <div className={styles.price}><Price price={_item.productPrice}/></div>
      </div>
      {/* P是套餐 S是單品 */}

      { _item.productType === 'S' ? getGoodsButton(_item)  : getPackButton(_item)}
    </li>)
  }

  return (
    <>
      { goodsModalVisable && <GoodsModal goodsDetail={goodsDetail} swiperRef={swiperRef} onClose={()=>setGoodsModalVisable(false)} banners={swiperImgs} /> }
      <SpecPicker onClose={()=>setSpecVisiable(false)} goodsDetail={goodsDetail} specVisiable={specVisiable}/>
      <div ref={props.menuRef} className={styles.right_content}>
        <div className={styles.list_box}>
            {categoryList && categoryList.map((item:any, index:number) => (
              <div className='menuItem'
                id={`menu_${item.categoryId}`} key={`menu_${item.categoryId}`}>
                <h3 className={styles.caption}>{item.categoryName}</h3>
                <ul className={styles._list_box}>
                  {item.productList.map((_item:any,  _index:number) => (
                    renderDataRow(_item, _index)
                  ))}
                </ul>
              </div>
            ))}
        </div>
      </div>
    </>
    );
}